package top.xia17.plugins.fast.common.spring.converter;


import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import org.springframework.lang.NonNull;
import top.xia17.plugins.fast.common.exceptions.BadRequestException;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 转换日期
 * @author xia17
 * @date 2019/5/25 14:52
 */
@Slf4j
public class LocalDateTimeConverter implements Converter<String,LocalDateTime> {


    /**
     * String to LocalDateTime
     * @param s 字符串
     * @return LocalDateTime
     */
    @Override
    public LocalDateTime convert(@NonNull String s) {
        String nullStr = "null";
        if ("".equals(s) || nullStr.equalsIgnoreCase(s)){
            return null;
        }
        try {
            LocalDate parse = LocalDate.parse(s, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            return parse.atStartOfDay();
        }catch (RuntimeException e){
            log.warn("参数转换Date异常："+ e.getMessage());
        }
        try {
            return LocalDateTime.parse(s,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }catch (RuntimeException e){
            log.error("参数转换DateTime异常"+ e.getMessage());
            throw new BadRequestException("在Controller转换日期格式时发生错误");
        }
    }
}
